import path from 'path'
import {stat} from 'fs/promises'
import { createReadStream } from 'fs';
import mime from 'mime'
export default function serve(dirname){
    return async (ctx,next)=>{
        let filePath = path.join(dirname,ctx.path);

        try{
            const statObj = await stat(filePath);
            if (statObj.isFile()) {
              ctx.set(
                "Content-Type",
                mime.getType(filePath) || "text/plain" + ";charset=utf-8"
              );
              ctx.body = createReadStream(filePath);
            } else {
              return next();
            }
        }catch(e){
            return next();
        }
        
    }
}